<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select v-model="query.dealer_id" filterable placeholder="所属单位" style="width: 185px;" class="filter-item">
          <el-option
            v-for="item in dict.dealers"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input v-model="query.eq_code" clearable placeholder="农机制造编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.eq_module" clearable placeholder="农机型号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.eq_type" filterable placeholder="农机类型">
          <el-option
              v-for="item in dict.equipment_type"
              :key="item.id"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-select v-model="query.interface_type" filterable placeholder="接口类型">
          <el-option
            v-for="item in dict.eq_interface_type"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-popover
            slot="right"
            placement="bottom-start"
            width="390"
            v-model="uploadFilePop"
            @hide="excelUploadHide"
        >
          <el-button
              slot="reference"
              v-if="crud.optShow.upload"
              class="filter-item"
              size="mini"
              type="danger"
              icon="el-icon-upload2"
          >导入</el-button>
          <el-upload
              ref="excelUpload"
              class="upload-demo"
              drag
              action="https://jsonplaceholder.typicode.com/posts/"
              :auto-upload="false"
              :limit = "1"
              :multiple="false"
              accept=".xls, .xlsx"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传excel文件</div>
          </el-upload>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="uploadFilePop=false">取消</el-button>
            <el-button type="primary" :loading="uploadFileLoading" size="mini" @click="doUpload">确定</el-button>
          </div>
        </el-popover>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="1200px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属单位" prop="dealer_id">
                <el-select v-model="form.dealer_id" filterable placeholder="请选择" style="width: 250px;">
                  <el-option
                      v-for="item in dict.dealers"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="农机制造编号" prop="eq_code">
                <el-input v-model="form.eq_code" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="农机名称" prop="eq_name">
                <el-input v-model="form.eq_name" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="农机类型" prop="eq_type">
                <el-select v-model="form.eq_type" filterable placeholder="请选择" style="width: 250px;">
                  <el-option
                      v-for="item in dict.equipment_type"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="农机型号" prop="eq_module">
                <el-input v-model="form.eq_module" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="农机品牌">
                <el-input v-model="form.eq_pingpai" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="农机生产企业">
                <el-input v-model="form.product_company" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="农机制造日期">
                <el-date-picker v-model="form.product_date" type="date" style="width: 250px;"  value-format="yyyy-MM-dd" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="农机制造厂家">
                <el-input v-model="form.eq_company" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="车牌号">
                <el-input v-model="form.eq_plat_number" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="作业幅宽(米)" >
                <el-input-number v-model="form.eq_work_width" :precision="2" :step="0.1" :max="99999999" style="width: 250px;"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="发动机品牌">
                <el-input v-model="form.engine_pingpai" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发动机型号">
                <el-input v-model="form.engine_module" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发动机型式">
                <el-input v-model="form.engine_type" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="发动机编号">
                <el-input v-model="form.engine_no" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发动机功率(Kw)">
                <el-input-number v-model="form.engine_power" :precision="2" :step="1" :max="99999999" style="width: 250px;"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发动机燃料类型">
                <el-input v-model="form.engine_fuel_type" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="发动机排放阶段">
                <el-input v-model="form.engine_out_type" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发动机生产企业">
                <el-input v-model="form.engine_company" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="环保公开编号">
                <el-input v-model="form.eq_no_a" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="机械环保代码">
                <el-input v-model="form.eq_no_b" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售状态">
                <el-input v-model="form.sales_status" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="接口类型" prop="interface_type">
                <el-select v-model="form.interface_type" filterable placeholder="请选择" style="width: 250px;">
                  <el-option
                      v-for="item in dict.eq_interface_type"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="平台对接码">
                <el-input v-model="form.interface_code" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否同步苏农云">
                <el-checkbox v-model="form.sync_sunong" style="width: 250px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="机主姓名">
                <el-input v-model="form.owner_name" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="机主电话">
                <el-input v-model="form.owner_phone" style="width: 250px;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" :rows="3" type="textarea" style="width: 635px;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="图片">
                <el-upload
                    ref="upload"
                    list-type="picture-card"
                    class="upload-demo"
                    action="#"
                    :file-list="fileList"
                    :auto-upload="false"
                >
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过512kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="dealer_name" label="所属单位" width="200" />
        <el-table-column   label="农机制造编号" width="100" fixed="left">
          <template slot-scope="scope">
            <router-link :to="'../equipmentDetial/detail/' + scope.row.eq_code">
              <div style="text-decoration: underline;color: blue;cursor: pointer;">{{scope.row.eq_code}}</div>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="eq_name" label="农机名称" width="200" />
        <el-table-column prop="eq_module" label="农机型号" width="200" />
        <el-table-column prop="eq_type" label="农机类型" width="100" />

        <el-table-column prop="sales_status" label="销售状态" width="100" />
        <el-table-column prop="interface_type" label="接口类型" width="100" />
        <el-table-column prop="interface_code" label="平台对接码" width="100" />
        <el-table-column prop="remark" label="备注" width="200" />
        <el-table-column v-if="checkPer(['admin','equipment:edit','equipment:del'])" label="操作" width="150px" align="center"
                         fixed="right">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import crudEquipment from '@/api/jf/equipment'
import CRUD, { presenter, header, form, crud } from '@crud/V2/crud'
import rrOperation from '@crud/V2/RR.operation'
import crudOperation from '@crud/V2/CRUD.operation'
import udOperation from '@crud/V2/UD.operation'
import pagination from '@crud/V2/Pagination'

const defaultForm = { id: '', dealer_id: '', eq_code: '', eq_type: '', eq_module: '', interface_type: '', product_date: '', engine_no: '', engine_type: '', engine_company: '', remark: '', images: [], eq_pingpai: '', product_company: '', eq_name: '', eq_work_width: 0, eq_plat_number: '', engine_pingpai: '', engine_module: '', engine_power: 0, engine_fuel_type: '', engine_out_type: '', eq_no_a: '', eq_no_b: '', sales_status: '', interface_code: '' ,eq_company: '',sync_sunong: 'N',owner_name:'',owner_phone:''}
export default {
  name: 'Equipment',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '设备基本信息', url: 'api/v2/base/equip/equipment', idField: 'id', sort: 'id,desc', crudMethod: { ...crudEquipment }})
  },
  dictsV2: ['dealers'],
  dicts: ['equipment_type', 'eq_interface_type'],
  data() {
    return {
      fileList: [{ id: '001', name: 'food.jpeg', url: '/api/v2/public/getImage?id=11' }],
      uploadFilePop: false,
      uploadFileLoading: false,
      permission: {
        add: ['admin', 'equipment:add'],
        edit: ['admin', 'equipment:edit'],
        del: ['admin', 'equipment:del']
      },
      rules: {
        dealer_id: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        eq_code: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        eq_name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        eq_type: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        eq_module: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        interface_type: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'dealer_id', display_name: '所属单位' },
        { key: 'eq_code', display_name: '农机制造编号' },
        { key: 'eq_module', display_name: '农机型号' },
        { key: 'interface_type', display_name: '接口类型' }
      ],
      fields: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created: function() {
    this.crud.optShow.upload = true
  },
  methods: {
    doUpload: function() {
      var files = this.$refs.excelUpload.uploadFiles
      if (files.length < 1) {
        this.crud.notify('请上传文件!', CRUD.NOTIFICATION_TYPE.ERROR)
        return
      }
      var params = {}
      params.excelFile = files[0].raw

      this.uploadFileLoading = true
      crudEquipment.excelUpload(params).then(res => {
        if (res.code === 1) {
          this.$notify({
            title: '上传成功',
            type: 'success',
            duration: 2500
          })
          this.crud.refresh()
        } else {
          this.crud.notify('上传失败!', CRUD.NOTIFICATION_TYPE.ERROR)
        }

        this.uploadFileLoading = false
        this.uploadFilePop = false
      }).catch(err => {
        this.uploadFileLoading = false
        console.log(err.response.data.message)
        this.uploadFilePop = false
      })
    },

    excelUploadHide: function() {
      this.$refs.excelUpload.clearFiles()
    },

    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      // console.log(form.images)
      this.fileList = []
      if (form.images != null) {
        for (let index = 0; index < form.images.length; index++) {
          const imageId = form.images[index]
          this.fileList.push({
            id: imageId,
            name: imageId,
            url: this.baseApi + '/api/v2/public/getImage?id=' + imageId
          })
        }
      }
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeValidateCU](crud) {
      // 检查并整理图片数据
      crud.form.oldImages = []
      crud.form.newImages = []
      var files = this.$refs.upload.uploadFiles
      for (var i = 0; i < files.length; i++) {
        var file = files[i]
        if (files[i].hasOwnProperty('raw')) {
          var imglist = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/gif']
          var isImage = imglist.some(function(item) {
            return item === file.raw.type
          })
          const isLt2M = file.raw.size / 1024 / 1024 < 0.5
          if (!isImage) {
            crud.notify('上传图片只能是图片格式!', CRUD.NOTIFICATION_TYPE.ERROR)
            return false
          }
          if (!isLt2M) {
            crud.notify('上传图片大小不能超过 512KB!', CRUD.NOTIFICATION_TYPE.ERROR)
            return false
          }
          crud.form.newImages.push(file.raw)
        } else {
          crud.form.oldImages.push(file.id)
        }
      }
      // magic-api不支持数组参数，转为字符
      // crud.form.oldImages = crud.form.oldImages.toString()
      return true
    },
    [CRUD.HOOK.afterValidateCU](crud) {
      // console.log(crud.form)
      // return
    },
    [CRUD.HOOK.afterSubmit](crud) {
      this.fileList = []
    },
    [CRUD.HOOK.beforeAddCancel](crud) {
      this.fileList = []
    },
    [CRUD.HOOK.beforeEditCancel](crud) {
      this.fileList = []
    }
  }
}
</script>

<style scoped>

</style>
